import { post, get, request } from '../http/request.js';

/**
 * Login with phone and password
 * @param {string} phone - Account phone number
 * @param {string} password - Account password
 * @returns {Promise} Response with token in header
 */
export async function loginWithPassword(phone, password) {
  try {
    const query = new URLSearchParams({ username: phone, password }).toString();
    const response = await request({
      url: `/user/username-token?${query}`,
      method: 'POST',
      header: {},
    });
    
    // Token is already extracted from response header by request.js
    return response;
  } catch (error) {
    console.error('Login failed:', error);
    throw error;
  }
}

/**
 * Get store list
 * @returns {Promise<Array>} Array of store objects with code, name, count, selected properties
 */
export async function getStoreList() {
  try {
    const response = await get('/client/count/store', null, {});
    
    if (response.data && response.data.code === 0 && Array.isArray(response.data.data)) {
      return response.data.data;
    }
    
    return [];
  } catch (error) {
    console.error('Get store list failed:', error);
    throw error;
  }
}

/**
 * Get task list (work kanban)
 * @param {Object} params - Request parameters
 * @param {number} params.current - Page number
 * @param {number} params.size - Page size
 * @param {string} params.dataScope - Data scope
 * @param {string} params.dataModel - Data model
 * @param {string} params.code - Code
 * @param {Array<string>} params.clientType - Client type array
 * @param {string} params.storeId - Store ID
 * @param {Object} params.orders - Order configuration
 * @returns {Promise<Array>} Array of vehicle data from clientVehicleList
 */
export async function getTaskList(params) {
  try {
    const response = await post('/client/work-kanban/list', params, {});
    
    if (response.data && response.data.code === 0 && response.data.data) {
      const list = response.data.data.records || response.data.data.list || [];
      
      // Extract clientVehicleList from each item
      const allVehicles = [];
      list.forEach(item => {
        if (item.clientVehicleList && Array.isArray(item.clientVehicleList)) {
          allVehicles.push(...item.clientVehicleList);
        }
      });
      
      return allVehicles;
    }
    
    return [];
  } catch (error) {
    console.error('Get task list failed:', error);
    throw error;
  }
}

/**
 * Get road data for a vehicle (maintenance points)
 * @param {string} userCarId - User car ID
 * @returns {Promise} Response with point data
 */
export async function getUserCarHome(userCarId) {
  try {
    const response = await get('/user-car/home', { userCarId }, {});
    return response;
  } catch (error) {
    console.error('Get user car home failed:', error);
    throw error;
  }
}

/**
 * Get maintenance records for a vehicle
 * @param {string} userCarId - User car ID
 * @param {string} type - Record type ('maint' or undefined for all)
 * @returns {Promise} Response with maintenance records
 */
export async function getMaintRecordList(userCarId, type) {
  try {
    const params = { userCarId };
    if (type) {
      params.type = type;
    }
    const response = await get('/maint/records', params, {});
    return response;
  } catch (error) {
    console.error('Get maintenance records failed:', error);
    throw error;
  }
}
